package zjut.raymond.witdemo.ui;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.alibaba.fastjson.JSON;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

import cn.finalteam.okhttpfinal.BaseHttpRequestCallback;
import cn.finalteam.okhttpfinal.HttpRequest;
import okhttp3.Headers;
import zjut.raymond.witdemo.R;
import zjut.raymond.witdemo.pojo.ReferencePoint;
import zjut.raymond.witdemo.ui.adapter.RPRecyclerViewAdapter;
import zjut.raymond.witdemo.util.ApiResult;
import zjut.raymond.witdemo.viewmodel.CollectorViewModel;

public class ListFragment extends Fragment implements View.OnClickListener {
    public static final String TAG = "ListFragment";
    private ScheduledExecutorService executorService;
    private SwipeRefreshLayout swipeRefreshLayout;
    private RecyclerView recyclerView;
    private FloatingActionButton actionButton;
    private RPRecyclerViewAdapter rpRecyclerViewAdapter;
    private CollectorViewModel collectorViewModel;
    private AddRPDialog addRPDialog = new AddRPDialog();

    public ListFragment() {
        // Required empty public constructor
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        collectorViewModel = new ViewModelProvider(getActivity()).get(CollectorViewModel.class);
        executorService = Executors.newScheduledThreadPool(5);
        initView();
        executorService.execute(runnable);
    }

    private void initView() {
        swipeRefreshLayout = getView().findViewById(R.id.swipe_refresh);
        recyclerView = getView().findViewById(R.id.recyclerViewRP);
        actionButton = getView().findViewById(R.id.fab);
        actionButton.setOnClickListener(this);
        rpRecyclerViewAdapter = new RPRecyclerViewAdapter();
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setAdapter(rpRecyclerViewAdapter);
        collectorViewModel.getReferencePointsLive().observe(getActivity(), referencePoints -> {
            Log.d(TAG, "initView: list changed");
            rpRecyclerViewAdapter.setReferencePoints(referencePoints);
            rpRecyclerViewAdapter.notifyDataSetChanged();
        });
        swipeRefreshLayout.setOnRefreshListener(() -> {
            executorService.execute(runnable);
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_list, container, false);
    }

    //
//    Runnable runnable = () -> OkHttpUtil.getInstance(MyApplication.getInstance()).getAsynHttp("http://47.101.186.100:9102/collector/getRps", new ResultCallback() {
//        @Override
//        public void onError(Request request, Exception e) {
//
//        }
//
//        @Override
//        public void onResponse(String responseData) throws IOException {
//            Log.d(TAG, "onResponse: " + responseData);
//            ApiResult apiResult = JSON.parseObject(responseData, ApiResult.class);
//            if (apiResult.getCode() == 200) {
//                List<Map<String, Object>> rpLists = (List<Map<String, Object>>) apiResult.getData();
//                for (Map<String, Object> rpMap : rpLists) {
//                    ReferencePoint referencePoint = JSON.parseObject(JSON.toJSONString(rpMap), ReferencePoint.class);
//                    collectorViewModel.addReferencePoint(referencePoint);
//                    Log.d(TAG, "onResponse: " + JSON.toJSONString(referencePoint));
//                }
//            }
//        }
//
//
//    });
    Runnable runnable = () -> HttpRequest.get("http://47.101.186.100:9102/collector/getRps", new BaseHttpRequestCallback<ApiResult>() {
        @Override
        protected void onSuccess(ApiResult apiResult) {
            if (apiResult.getCode() == 200) {
                collectorViewModel.clearReferencePoint();
                List<Map<String, Object>> rpLists = (List<Map<String, Object>>) apiResult.getData();
                for (Map<String, Object> rpMap : rpLists) {
                    ReferencePoint referencePoint = JSON.parseObject(JSON.toJSONString(rpMap), ReferencePoint.class);
                    collectorViewModel.addReferencePoint(referencePoint);
                    Log.d(TAG, "onSuccess: " + JSON.toJSONString(referencePoint));
                }
                swipeRefreshLayout.setRefreshing(false);
            }
        }
    });

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.fab: {
                addRPDialog.show(getParentFragmentManager(), "AddRpDialog");
            }
            break;
            default:
                break;
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        executorService.shutdown();
    }
}